// 校园失物招领平台 - JavaScript功能实现

// DOM元素引用
const publishBtn = document.getElementById('publishBtn');
const publishModal = document.getElementById('publishModal');
const messageModal = document.getElementById('messageModal');
const postsContainer = document.getElementById('postsContainer');
const filterForm = document.getElementById('filterForm');
const closePublishModal = document.getElementById('closePublishModal');
const closeMessageModal = document.getElementById('closeMessageModal');
const submitPublishBtn = document.getElementById('submitPublishBtn');
const submitMessageBtn = document.getElementById('submitMessageBtn');
const resetFilterBtn = document.getElementById('resetFilterBtn');
const postDetailContainer = document.getElementById('postDetail');
const messagesContainer = document.getElementById('messagesContainer');
const messageContentInput = document.getElementById('messageContent');
const messageContactInput = document.getElementById('messageContact');

// 常量定义
const EXPIRE_DAYS = 7;
const STORAGE_KEY = 'campusLostFoundPosts';

// 当前选中的帖子ID
let currentPostId = null;

// 初始化应用
function initApp() {
    console.log('初始化应用...');
    // 加载并显示帖子
    loadAndDisplayPosts();
    // 绑定事件监听器
    bindEventListeners();
}

// 绑定事件监听器
function bindEventListeners() {
    // 发布按钮
    publishBtn.addEventListener('click', () => openModal(publishModal));
    
    // 关闭按钮
    closePublishModal.addEventListener('click', () => closeModal(publishModal));
    closeMessageModal.addEventListener('click', () => closeModal(messageModal));
    
    // 提交发布
    submitPublishBtn.addEventListener('click', publishPost);
    
    // 提交留言
    submitMessageBtn.addEventListener('click', submitMessage);
    
    // 筛选表单
    filterForm.addEventListener('submit', filterPosts);
    resetFilterBtn.addEventListener('click', resetFilter);
    
    // 点击模态框外部关闭
    publishModal.addEventListener('click', (e) => {
        if (e.target === publishModal) closeModal(publishModal);
    });
    
    messageModal.addEventListener('click', (e) => {
        if (e.target === messageModal) closeModal(messageModal);
    });
    
    // ESC键关闭模态框
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
            closeModal(publishModal);
            closeModal(messageModal);
        }
    });
}

// 打开模态框
function openModal(modal) {
    modal.style.display = 'flex';
    // 添加延迟以触发动画
    setTimeout(() => {
        modal.classList.add('active');
    }, 10);
}

// 关闭模态框
function closeModal(modal) {
    modal.classList.remove('active');
    // 等待动画完成后隐藏
    setTimeout(() => {
        modal.style.display = 'none';
    }, 300);
    
    // 重置表单
    if (modal === publishModal) {
        document.getElementById('publishForm').reset();
    } else if (modal === messageModal) {
        document.getElementById('messageForm').reset();
    }
}

// 从LocalStorage获取帖子数据
function getPostsFromStorage() {
    try {
        const posts = localStorage.getItem(STORAGE_KEY);
        const parsed = posts ? JSON.parse(posts) : [];
        // 确保返回的是数组
        return Array.isArray(parsed) ? parsed : [];
    } catch (e) {
        console.error('获取数据失败:', e);
        return [];
    }
}

// 保存帖子数据到LocalStorage
function savePostsToStorage(posts) {
    try {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(posts));
        return true;
    } catch (e) {
        console.error('保存数据失败:', e);
        alert('存储数据时出错，请检查浏览器存储空间是否充足。');
        return false;
    }
}

// 生成唯一ID
function generateUniqueId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2, 9);
}

// 检查帖子是否过期（7天）
function isPostExpired(postDate) {
    try {
        const sevenDaysAgo = new Date();
        sevenDaysAgo.setDate(sevenDaysAgo.getDate() - EXPIRE_DAYS);
        const postDateTime = new Date(postDate).getTime();
        return postDateTime < sevenDaysAgo.getTime();
    } catch (e) {
        console.error('日期解析错误:', e);
        return false;
    }
}

// 格式化日期
function formatDate(date) {
    try {
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    } catch (e) {
        console.error('日期格式化错误:', e);
        return '无效日期';
    }
}

// 格式化相对时间
function formatRelativeTime(date) {
    try {
        const now = new Date();
        const past = new Date(date);
        const diffMs = now - past;
        const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
        const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
        const diffMinutes = Math.floor(diffMs / (1000 * 60));
        
        if (diffDays > 0) {
            return `${diffDays}天前`;
        } else if (diffHours > 0) {
            return `${diffHours}小时前`;
        } else if (diffMinutes > 0) {
            return `${diffMinutes}分钟前`;
        } else {
            return '刚刚';
        }
    } catch (e) {
        console.error('相对时间计算错误:', e);
        return '';
    }
}

// 显示提示消息（替代alert）
function showNotification(message, type = 'success') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;
    
    // 设置样式
    notification.style.position = 'fixed';
    notification.style.bottom = '20px';
    notification.style.right = '20px';
    notification.style.padding = '15px 20px';
    notification.style.borderRadius = '8px';
    notification.style.color = 'white';
    notification.style.fontWeight = '500';
    notification.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
    notification.style.zIndex = '9999';
    notification.style.opacity = '0';
    notification.style.transition = 'opacity 0.3s ease';
    
    // 根据类型设置背景色
    if (type === 'error') {
        notification.style.backgroundColor = '#e74c3c';
    } else {
        notification.style.backgroundColor = '#2ecc71';
    }
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 显示通知
    setTimeout(() => {
        notification.style.opacity = '1';
    }, 10);
    
    // 3秒后隐藏
    setTimeout(() => {
        notification.style.opacity = '0';
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

// 发布新帖子
function publishPost() {
    try {
        // 获取表单数据
        const postType = document.querySelector('input[name="postType"]:checked').value;
        const title = document.getElementById('postTitle').value.trim();
        const category = document.getElementById('postCategory').value;
        const location = document.getElementById('postLocation').value.trim();
        const description = document.getElementById('postDescription').value.trim();
        const contact = document.getElementById('postContact').value.trim();
        
        // 简单验证
        if (!title || !location || !description || !contact || !category) {
            showNotification('请填写所有必填字段！', 'error');
            return;
        }
        
        // 创建帖子对象
        const newPost = {
            id: generateUniqueId(),
            type: postType,
            title,
            category,
            location,
            description,
            contact,
            date: new Date().toISOString(),
            createdAt: new Date().toISOString(), // 添加创建时间用于排序
            messages: []
        };
        
        // 获取现有帖子
        const posts = getPostsFromStorage();
        
        // 添加新帖子
        posts.unshift(newPost); // 添加到开头
        
        // 保存到LocalStorage
        if (savePostsToStorage(posts)) {
            // 重新加载和显示帖子
            loadAndDisplayPosts();
            
            // 显示成功提示
            showNotification('发布成功！');
            
            // 关闭模态框
            closeModal(publishModal);
        }
    } catch (e) {
        console.error('发布帖子失败:', e);
        showNotification('发布失败，请重试！', 'error');
    }
}

// 加载并显示帖子
function loadAndDisplayPosts(filteredPosts = null) {
    // 显示加载状态
    postsContainer.innerHTML = '<div class="loading"></div>';
    
    // 使用setTimeout模拟异步加载，提升用户体验
    setTimeout(() => {
        // 如果没有传入筛选后的帖子，则获取所有帖子
        let posts = filteredPosts || getPostsFromStorage();
        
        // 如果有createdAt字段，按创建时间排序，否则按date字段排序
        if (posts.length > 0) {
            posts = [...posts].sort((a, b) => {
                const dateA = a.createdAt ? new Date(a.createdAt).getTime() : new Date(a.date).getTime();
                const dateB = b.createdAt ? new Date(b.createdAt).getTime() : new Date(b.date).getTime();
                return dateB - dateA; // 降序排序，最新的在前
            });
        }
        
        // 清空容器
        postsContainer.innerHTML = '';
        
        // 检查是否有帖子
        if (posts.length === 0) {
            postsContainer.innerHTML = `
                <div class="empty-state">
                    <h3>暂无相关信息</h3>
                    <p>还没有找到你想要的信息，试试调整筛选条件或发布新的信息吧！</p>
                    <button class="btn-primary" onclick="document.getElementById('publishBtn').click()">发布信息</button>
                </div>
            `;
            return;
        }
        
        // 渲染帖子
        posts.forEach(post => {
            const isExpired = isPostExpired(post.date);
            const postCard = document.createElement('div');
            postCard.className = `post-card ${post.type} ${isExpired ? 'expired' : ''}`;
            
            // 生成相对时间
            const relativeTime = formatRelativeTime(post.date);
            
            postCard.innerHTML = `
                <div class="post-header">
                    <span class="post-type ${post.type}">${post.type === 'lost' ? '寻物启事' : '失物招领'}</span>
                    <span class="post-date">${formatDate(post.date)} (${relativeTime})</span>
                </div>
                <h3 class="post-title">${post.title}</h3>
                <div class="post-location">${post.location}</div>
                <div class="post-info">
                    <span>${post.category}</span>
                    <span class="post-status ${isExpired ? 'expired' : 'active'}">${isExpired ? '已过期' : '进行中'}</span>
                </div>
                <p class="post-description">${post.description}</p>
                <button class="contact-btn" data-id="${post.id}">查看详情</button>
            `;
            
            postsContainer.appendChild(postCard);
            
            // 绑定详情按钮事件
            const contactBtn = postCard.querySelector('.contact-btn');
            contactBtn.addEventListener('click', () => showPostDetail(post.id));
        });
    }, 300); // 300ms延迟，让加载动画显示
}

// 显示帖子详情和留言
function showPostDetail(postId) {
    try {
        const posts = getPostsFromStorage();
        const post = posts.find(p => p.id === postId);
        
        if (!post) {
            showNotification('帖子不存在！', 'error');
            return;
        }
        
        // 保存当前帖子ID
        currentPostId = postId;
        
        // 渲染帖子详情
        const isExpired = isPostExpired(post.date);
        const relativeTime = formatRelativeTime(post.date);
        
        postDetailContainer.innerHTML = `
            <h4>${post.title}</h4>
            <p><strong>类型：</strong>${post.type === 'lost' ? '寻物启事' : '失物招领'}</p>
            <p><strong>物品类别：</strong>${post.category}</p>
            <p><strong>地点：</strong>${post.location}</p>
            <p><strong>发布时间：</strong>${formatDate(post.date)} (${relativeTime})</p>
            <p><strong>状态：</strong><span class="post-status ${isExpired ? 'expired' : 'active'}">${isExpired ? '已过期' : '进行中'}</span></p>
            <p><strong>描述：</strong>${post.description}</p>
            <p><strong>联系方式：</strong>${post.contact}</p>
        `;
        
        // 确保messages属性存在
        if (!post.messages) {
            post.messages = [];
        }
        
        // 渲染留言列表
        renderMessages(post.messages);
        
        // 打开留言模态框
        openModal(messageModal);
    } catch (e) {
        console.error('显示帖子详情失败:', e);
        showNotification('加载详情失败，请重试！', 'error');
    }
}

// 渲染留言列表
function renderMessages(messages) {
    messagesContainer.innerHTML = '';
    
    if (!messages || messages.length === 0) {
        messagesContainer.innerHTML = '<p style="text-align: center; color: #94a3b8;">暂无留言</p>';
        return;
    }
    
    // 按时间排序（最新的在最后）
    const sortedMessages = [...messages].sort((a, b) => {
        return new Date(a.date).getTime() - new Date(b.date).getTime();
    });
    
    sortedMessages.forEach(message => {
        const messageItem = document.createElement('div');
        messageItem.className = 'message-item';
        const relativeTime = formatRelativeTime(message.date);
        
        messageItem.innerHTML = `
            <div class="message-header">${formatDate(message.date)} · ${relativeTime}</div>
            <div class="message-content">${message.content}</div>
            <div class="message-contact">联系方式：${message.contact}</div>
        `;
        messagesContainer.appendChild(messageItem);
    });
    
    // 滚动到底部
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
}

// 提交留言
function submitMessage() {
    try {
        const content = messageContentInput.value.trim();
        const contact = messageContactInput.value.trim();
        
        if (!content || !contact) {
            showNotification('请填写留言内容和联系方式！', 'error');
            return;
        }
        
        // 获取帖子
        const posts = getPostsFromStorage();
        const postIndex = posts.findIndex(p => p.id === currentPostId);
        
        if (postIndex === -1) {
            showNotification('帖子不存在！', 'error');
            closeModal(messageModal);
            return;
        }
        
        // 确保messages数组存在
        if (!posts[postIndex].messages) {
            posts[postIndex].messages = [];
        }
        
        // 创建留言对象
        const newMessage = {
            id: generateUniqueId(),
            content,
            contact,
            date: new Date().toISOString()
        };
        
        // 添加留言
        posts[postIndex].messages.push(newMessage);
        
        // 保存到LocalStorage
        if (savePostsToStorage(posts)) {
            // 更新显示
            renderMessages(posts[postIndex].messages);
            
            // 清空表单
            messageContentInput.value = '';
            messageContactInput.value = '';
            
            // 显示成功提示
            showNotification('留言成功！');
        }
    } catch (e) {
        console.error('提交留言失败:', e);
        showNotification('留言失败，请重试！', 'error');
    }
}

// 筛选帖子
function filterPosts(e) {
    e.preventDefault();
    
    // 获取筛选条件
    const typeFilter = document.getElementById('filterType').value;
    const categoryFilter = document.getElementById('filterCategory').value;
    const locationFilter = document.getElementById('filterLocation').value.trim().toLowerCase();
    
    // 获取所有帖子
    const allPosts = getPostsFromStorage();
    
    // 筛选
    const filtered = allPosts.filter(post => {
        // 类型筛选
        if (typeFilter && post.type !== typeFilter) return false;
        
        // 类别筛选
        if (categoryFilter && post.category !== categoryFilter) return false;
        
        // 地点筛选（模糊匹配）
        if (locationFilter && !post.location.toLowerCase().includes(locationFilter)) return false;
        
        return true;
    });
    
    // 显示筛选结果
    loadAndDisplayPosts(filtered);
}

// 重置筛选
function resetFilter() {
    filterForm.reset();
    loadAndDisplayPosts();
}

// 当文档加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('页面加载完成，开始初始化应用...');
    
    // 首先添加示例数据
    addSampleData();
    
    // 然后初始化应用
    initApp();
});

// 添加一些示例数据（如果没有数据的话）
function addSampleData() {
    try {
        const posts = getPostsFromStorage();
        
        if (posts.length === 0) {
            console.log('没有找到现有数据，添加示例数据...');
            
            const samplePosts = [
                {
                    id: generateUniqueId(),
                    type: 'found',
                    title: '捡到校园卡一张',
                    category: '证件类',
                    location: '第一食堂',
                    description: '今日中午在第一食堂二楼捡到一张校园卡，姓名：张同学，学号：20210001，请失主联系认领。',
                    contact: '微信：zhangsan123',
                    date: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(),
                    createdAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(),
                    messages: [
                        {
                            id: generateUniqueId(),
                            content: '这是我的卡！请问可以现在领取吗？',
                            contact: '电话：13800138001',
                            date: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString()
                        }
                    ]
                },
                {
                    id: generateUniqueId(),
                    type: 'lost',
                    title: '丢失黑色笔记本电脑',
                    category: '电子设备',
                    location: '图书馆自习室',
                    description: '昨天下午在图书馆二楼自习室丢失一台黑色联想ThinkPad笔记本电脑，电脑包上有学校标志，请拾到者联系，必有重谢！',
                    contact: '电话：13900139000',
                    date: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString(),
                    createdAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString(),
                    messages: []
                },
                {
                    id: generateUniqueId(),
                    type: 'lost',
                    title: '丢失蓝色书包',
                    category: '背包类',
                    location: '第三教学楼',
                    description: '今天上午在第三教学楼302教室丢失一个蓝色书包，内有课本和笔记本，书包上有小熊挂件。',
                    contact: 'QQ：123456789',
                    date: new Date(Date.now() - 8 * 24 * 60 * 60 * 1000).toISOString(),
                    createdAt: new Date(Date.now() - 8 * 24 * 60 * 60 * 1000).toISOString(),
                    messages: []
                },
                {
                    id: generateUniqueId(),
                    type: 'found',
                    title: '捡到一副耳机',
                    category: '电子设备',
                    location: '第二教学楼',
                    description: '在第二教学楼501教室捡到一副白色AirPods Pro耳机，放在讲台旁边，请失主联系认领。',
                    contact: '请联系第二教学楼前台',
                    date: new Date().toISOString(),
                    createdAt: new Date().toISOString(),
                    messages: []
                }
            ];
            
            savePostsToStorage(samplePosts);
            console.log('示例数据添加成功');
        }
    } catch (e) {
        console.error('添加示例数据失败:', e);
    }
}